//
//  AreaTableViewController.m
//  AIM
//
//  Created by user10 on 2017/5/18.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "AreaTableViewController.h"
#import "FriendHeader.h"
#import "AreaCell.h"
#import "NetWorkTools.h"
#import "NomalModel.h"

// 遵守FriendHeaderDelegate协议
@interface AreaTableViewController() <FriendHeaderDelegate>

@property(nonatomic, strong) NSMutableArray *areaArr;
@property(nonatomic, strong) NSMutableArray *groupArray;
@property(nonatomic, strong) NSMutableArray *childArray;
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation AreaTableViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _areaArr = [NSMutableArray array];
//    _historyArr = [NSMutableArray array];
    self.tableView.allowsMultipleSelectionDuringEditing=YES;
    // Do any additional setup after loading the view, typically from a nib.
    
    self.tableView.sectionHeaderHeight = 44;
    NSString *webServiceStr = [NSString stringWithFormat:
                               @"<web:getPostToData>\
                               <arg0>%@</arg0>\
                               </web:getPostToData>",COMPANY];
    //初始化网络工具类
    NetWorkTools *tools = [NetWorkTools shareTools];
    //发送网络请求
    [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostToImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *string = result;
        NSRange startRange = [string rangeOfString:@"@@"];
        NSRange endRange = [string rangeOfString:@"</return>"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        if (range.location != NSNotFound) {
            NSString *resultString = [string substringWithRange:range];
            
            NSData * getJsonData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];
            _groupArray= [getDict objectForKey:@"GROUP_DATA"];
            _childArray = [getDict objectForKey:@"CHILD_DATA"];
            
            if (_groupArray.count == _childArray.count) {
                
                
                for (int i = 0 ; i < _groupArray.count ; i++) {
                    
                    
                    NSDictionary *dic = _groupArray[i];
                    NomalModel *model = [[NomalModel alloc] init];
                    model.MSG_CATEGORY_TO_CD = [dic objectForKey:@"MSG_CATEGORY_TO_CD"];
                    model.MSG_CATEGORY_TO_CHECKED = [dic objectForKey:@"MSG_CATEGORY_TO_CHECKED"];
                    model.MSG_CATEGORY_TO_NM = [dic objectForKey:@"MSG_CATEGORY_TO_NM"];
                    
                    
                    
                    for (NSDictionary *areaDic in _childArray[i]) {
                        
                        NomalModel *areaModel = [[NomalModel alloc] init];
                        areaModel.MSG_CATEGORY_TO_CD = [areaDic objectForKey:@"MSG_CATEGORY_TO_CD"];
                        areaModel.MSG_CATEGORY_TO_CHECKED = [areaDic objectForKey:@"MSG_CATEGORY_TO_CHECKED"];
                        areaModel.MSG_CATEGORY_TO_NM = [areaDic objectForKey:@"MSG_CATEGORY_TO_NM"];
                        
                        [model.areaArray addObject:areaModel];
                    }
                    
                    
                    [self.dataArray addObject:model];
                }
                
            }
            for (NSDictionary *dic in _historyArr) {
                NSString *MSG_SEND_GROUP_TO = [dic objectForKey:@"MSG_SEND_GROUP_TO"];
                NSString *MSG_SEND_TO = [dic objectForKey:@"MSG_SEND_TO"];
                for (int i = 0; i < self.dataArray.count; i++) {
                    NomalModel *model = self.dataArray[i];
                    if ([model.MSG_CATEGORY_TO_CD isEqualToString:MSG_SEND_GROUP_TO]) {
                        for (int j = 0;j< model.areaArray.count; j++) {
                            NomalModel *areamodel = model.areaArray[j];
                            if ([areamodel.MSG_CATEGORY_TO_CD isEqualToString:MSG_SEND_TO]) {
                                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
                                [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
                            }
                        }
                    }
                }
            }
            
            
            [self.tableView reloadData];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Network error" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }
        
        
    }];
}


- (NSMutableArray *)dataArray {

    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
        
    }
    return _dataArray;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - dataSource方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NomalModel *model = self.dataArray[section];
    
    
    return model.isOpen? model.areaArray.count : 0;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"areaCell";
    
    AreaCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (nil == cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"AreaCell"  owner:self options:nil] lastObject];
    }
    
    NomalModel *model = self.dataArray[indexPath.section];
    model.MSG_CATEGORY_INDEX = indexPath;
    NomalModel *areaModel = model.areaArray[indexPath.row];
    areaModel.MSG_CATEGORY_INDEX = indexPath;
    
    cell.nomalData = areaModel;
    cell.textLabel.backgroundColor = [UIColor clearColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(AreaCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (cell.nomalData.isSelect) {
        cell.selImage.hidden = NO;
        cell.backgroundColor = [UIColor magentaColor];
        
        cell.textLabel.backgroundColor = [UIColor clearColor];
    }else if(!cell.nomalData.isSelect){
        cell.selImage.hidden = YES;
        cell.backgroundColor = [UIColor clearColor];
        
        cell.textLabel.backgroundColor = [UIColor clearColor];
    }
    
//    NomalModel *model = self.dataArray[indexPath.section];
//    model.MSG_CATEGORY_INDEX = indexPath;
//    NomalModel *areaModel = model.areaArray[indexPath.row];
//    areaModel.MSG_CATEGORY_INDEX = indexPath;
//    
//    for (NSDictionary *dict in _historyArr) {
//        NSLog(@"%@------%@",[dict objectForKey:@"MSG_SEND_GROUP_TO"],model.MSG_CATEGORY_TO_CD);
//        if ([[dict objectForKey:@"MSG_SEND_GROUP_TO"]isEqualToString:model.MSG_CATEGORY_TO_CD]) {
//            model.isSelect = YES;
//        }else if ([[dict objectForKey:@"MSG_SEND_TO"]isEqualToString:areaModel.MSG_CATEGORY_TO_CD]){
//            model.isSelect = YES;
//        }
//    }
    
}

#pragma mark 选中行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    AreaCell *nowCell = [tableView cellForRowAtIndexPath:indexPath];
//    nowCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NomalModel *model = self.dataArray[indexPath.section];
    
    NomalModel *areaModel = model.areaArray[indexPath.row];
    
    
    NSLog(@"{SHARE_TO_GROUP = %@ SHARE_TO_SHOP = %@}", model.MSG_CATEGORY_TO_CD, areaModel.MSG_CATEGORY_TO_CD);
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:areaModel.MSG_CATEGORY_TO_CD forKey:@"SHARE_TO_SHOP"];
    [dict setObject:model.MSG_CATEGORY_TO_CD forKey:@"SHARE_TO_GROUP"];
//    [dict setObject:areaModel.MSG_CATEGORY_TO_CD forKey:@"SHARE_TO_SHOP"];
//    [dict setObject:model.MSG_CATEGORY_TO_CD forKey:@"SHARE_TO_GROUP"];
    
    if (areaModel.isSelect) {
        areaModel.isSelect = NO;
        
        if ([self.areaDelegate respondsToSelector:@selector(areaValuesDelFromDict:)]) {
            // 调用代理对象的刷新方法，代理对象去实现方法
            [self.areaDelegate areaValuesDelFromDict:dict];
        }
    }else{
        areaModel.isSelect = YES;
        if ([self.areaDelegate respondsToSelector:@selector(areaValuesWithDict:)]) {
            // 调用代理对象的刷新方法，代理对象去实现方法
            [self.areaDelegate areaValuesWithDict:dict];
        }
    }
    
    for (NomalModel *arenomal in model.areaArray) {
        model.isSelect = YES;
        if (arenomal.isSelect == NO) {
            model.isSelect = NO;
            break;
        }
    }
    
    [self.tableView reloadData];
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NomalModel *model = self.dataArray[indexPath.section];
    
    NomalModel *areaModel = model.areaArray[indexPath.row];
    areaModel.isSelect = NO;
    [self.tableView reloadData];
}


/** 自定义每个section的头部 */
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    FriendHeader *header = [FriendHeader friendHeaderWithTableView:self.tableView];
    // 加载数据
    header.nomalModel = self.dataArray[section];
    // 设置代理
    header.delegate = self;
    return header;
}

#pragma mark - FriendHeaderDelegate方法
- (void)friendHeaderDidClickedHeader:(FriendHeader *)header {
    // 刷新数据
    [self.tableView reloadData];
}

- (void)fireadHeadDidSelect:(FriendHeader *)header {

    if (header.nomalModel.isSelect) {
        
        NSMutableArray *array = [NSMutableArray array];
        NSLog(@"%@",header.nomalModel.areaArray);
        
        for (NomalModel *model in  header.nomalModel.areaArray) {
            model.isSelect = YES;
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setObject:header.nomalModel.MSG_CATEGORY_TO_CD forKey:@"SHARE_TO_GROUP"];
                [dict setObject:model.MSG_CATEGORY_TO_CD forKey:@"SHARE_TO_SHOP"];
                [array addObject:dict];
                    NSLog(@"%@",dict);
        }
        if (self.areaDelegate && [self.areaDelegate respondsToSelector:@selector(areaValuesWithDictArray:)]) {
            
            [self.areaDelegate areaValuesWithDictArray:array];
        }
        
    } else {
          NSMutableArray *array = [NSMutableArray array];
        for (NomalModel *model in  header.nomalModel.areaArray) {
            model.isSelect = NO;
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:header.nomalModel.MSG_CATEGORY_TO_CD forKey:@"SHARE_TO_GROUP"];
            [dict setObject:model.MSG_CATEGORY_TO_CD forKey:@"SHARE_TO_SHOP"];
            [array addObject:dict];
        }
        
        if (self.areaDelegate && [self.areaDelegate respondsToSelector:@selector(areaValuesDelFromDictArray:)]) {
            
            [self.areaDelegate areaValuesDelFromDictArray:array];
        }

        
    }
    
    [self.tableView reloadData];
}


@end
